package com.muchenx.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
public final class ReflectUtil {
 
    public static Field getField(Class<?> cls, String fieldName) {
        Class<?> sCls = cls;
        do {
            try {
                return sCls.getDeclaredField(fieldName);
            } catch (NoSuchFieldException ignored) {
                sCls = sCls.getSuperclass();
            }
        } while (!Object.class.equals(sCls));
        throw new RuntimeException("no such field[" + fieldName + "] in class [" + cls + "]");
    }
 
    public static Field getField(Object obj, String fieldName) {
        return getField(obj.getClass(), fieldName);
    }
 
    public static List<Field> getAllFields(Class<?> cls) {
        List<Field> fields = new ArrayList<>();
        Class<?> sCls = cls;
        do {
            fields.addAll(Arrays.asList(sCls.getDeclaredFields()));
            sCls = sCls.getSuperclass();
        } while (!Object.class.equals(sCls));
        return fields;
    }
 
    public static List<Field> getAllFields(Object obj) {
        return getAllFields(obj.getClass());
    }
 
    public static void set(Object obj, Field f, Object v) {
        try {
            f.set(obj, v);
        } catch (IllegalAccessException e) {
            f.setAccessible(true);
            try {
                f.set(obj, v);
            } catch (IllegalAccessException ignored) {
            }
        }
    }
 
    public static void set(Object obj, String fieldName, Object v) {
        set(obj, getField(obj, fieldName), v);
    }
 
    public static Object get(Object obj, Field f) {
        try {
            return f.get(obj);
        } catch (IllegalAccessException e) {
            try {
                f.setAccessible(true);
                return f.get(obj);
            } catch (IllegalAccessException ignored) {
                return null;
            }
        }
    }
 
    public static Object get(Object obj, String fieldName) {
        return get(obj, getField(obj, fieldName));
    }
 
}